<?php
/**
* designer.php
*
* Create on 2015-12-2
* Create by TT
*/
namespace haibao\cms\data;

use \haibao\cms\model\filter\Designer\Designer as DesignerFilter;
use \haibao\cms\model\filter\Designer\DesignerRelBrand as DesignerRelBrandFilter;
use \haibao\cms\model\filter\Designer\DesignerRelCelebrity as DesignerRelCelebrityFilter;
use \haibao\cms\model\data\Designer\DesignerRelBrand as DesignerRelBrandData;
use \haibao\cms\model\data\Designer\DesignerRelCelebrity as DesignerRelCelebrityData;
use \haibao\frame\data\query\Condition ;
use haibao\cms\model\data\designer\DesignerRelCelebrity;

class Designer extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\designer\Designer');
	}
	
	private static $all = '全部';
	
	public function getBrands($brandsArr = null){
		$containType = '';
		if($brandsArr){
			$containType = "  where b.BrandId in (".implode(',', $brandsArr).")";
		}
		$brands = array();
		$sql = "select a.NameCN,a.NameEN,b.DesignerId,b.BrandId from Brand as a left join DesignerRelBrand as b on a.Id = b.BrandId $containType";
		$result = $this->query($sql);
		while($row = $result->fetch_assoc()){	
			if($row['BrandId']){
				$brands[$row['BrandId']] = $row['NameCN'];
			}
		}
		return $brands;
	}
	
	public function addDesignerClickNum($designerId){
		$sql = 'update DesignerProperty set ClickNum=ClickNum+1,EditClickNum=EditClickNum+1 where DesignerId=%s';
		$result  = $this->query($sql,array($designerId));
	}
	
	/**
	 * 获取所有品牌
	 * @return multitype:NULL
	 */
	public function getAllBrands(){
		$cache = new \haibao\cms\cache\Designer();
		$brands = $cache->getDesignerBrandCache(\haibao\cms\model\data\designer\Designer::DESIGNER_BRAND_CACHE_KEY);
		if(empty($brands)){
			$brands = $this->setBrandsCache();
		}
		return $brands;
	}
	
	public function getBrandsByLetter($letterLow){
		$cache = new \haibao\cms\cache\Designer();
		$brands = $cache->getDesignerBrandCache(\haibao\cms\model\data\designer\Designer::DESIGNER_BRAND_TYPE_CACHE_KEY);
		if(!isset($brands[$letterLow])){
			$brands[$letterLow] = $this->setBrandsCache($letterLow);
		}
		return isset($brands[$letterLow]) ? $brands[$letterLow] : array();
	}
	
	/**
	 * 品牌缓存
	 * @return multitype:NULL
	 */
	public function setBrandsCache($letterLow = null){
		$containType = '';
		if($letterLow){
			if($letterLow != self::$all){
				$containType = "  where b.PinyinEN = '$letterLow'";
			}
		}
		$brands = array();
		$sql = "select b.Id,b.NameCN,b.NameEN,a.BrandId from DesignerRelBrand as a left join Brand as b on b.Id = a.BrandId $containType order by b.Id";
		$result = $this->query($sql);
		while($row = $result->fetch_assoc()){
			if($row['Id']){
				$brands[$row['Id']] = $row['NameCN'].'&nbsp;'.$row['NameEN'];
				//$brands[$row['BrandId']] = $row['NameEN'];
			}
		}
		$cache = new \haibao\cms\cache\Designer();
		if($letterLow){
			$letterArr = $cache->getDesignerBrandCache(\haibao\cms\model\data\designer\Designer::DESIGNER_BRAND_TYPE_CACHE_KEY);
			$letterArr[$letterLow] = $brands;
			$cache->setDesignerBrandCache(\haibao\cms\model\data\designer\Designer::DESIGNER_BRAND_TYPE_CACHE_KEY, $letterArr);
		}else {
			$cache->setDesignerBrandCache(\haibao\cms\model\data\designer\Designer::DESIGNER_BRAND_CACHE_KEY, $brands);
		}
		return $brands;
	}


	public function getDesignerByBrandId($brandId,$typeArr){
		$deignerIdArr = array();
		if(is_array($typeArr) && !empty($typeArr)){
			$str = preg_replace('/\d+/', '%s', implode(',', $typeArr));
			$sql = 'select DesignerId,BrandId from DesignerRelBrand where  RelType in ('.$str.') and BrandId = %s';
			array_push($typeArr,$brandId);
			$designerResult = $this->query($sql,$typeArr);
		}else {
			$sql = 'select DesignerId,BrandId from DesignerRelBrand where RelType =%s and BrandId = %s';
			$designerResult = $this->query($sql,array(\haibao\cms\model\data\designer\DesignerRelBrand::RELTYPE_NOW,$brandId));
		}
		while($row = $designerResult->fetch_assoc()){
			$deignerIdArr[] = $row['DesignerId'];
		}
		return $deignerIdArr;
	}
	
	
	/**
	 * 获取设计师总数量
	 */
	public function getDesignerListCount(){
		$sql = 'select count(*) as designerNum from Designer where Status = %s';
		return $this->query($sql,array(\haibao\cms\model\data\designer\Designer::STATUS_ENABLE))->fetch_assoc();
	}
	
	/**
	 * 通过设计师ID获取粉丝数 EditFansNum
	 */
	public function getDeisgnerFansNumByDesignerId($designerId,$type){
		$result = array();
		if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
			$sql = 'select EditFansNum from DesignerProperty where DesignerId = %s';
		}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
			$sql = 'select EditClickNum from DesignerProperty where DesignerId = %s';
		}
		$result = $this->query($sql,array($designerId))->fetch_assoc();
		return $result;
	}
	
	/**
	 * 通过设计师ID修改粉丝数 EditFansNum
	 * @param string $editFansNum 粉丝数/点击量
	 * @param string $designerId 设计师ID
	 * @param string $type 类型（粉丝数/点击量）
	 */
	
	public function editDesignerFansNumByDesignerId($editFansNum,$designerId,$type){
		if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
			$sql = 'update DesignerProperty set EditFansNum = %s where DesignerId = %s';
		}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
			$sql = 'update DesignerProperty set EditClickNum = %s where DesignerId = %s';
		}
		$this->query($sql,array($editFansNum,$designerId));
	}
	
	public function updateCommentNum($designerId,$userId,$num = 1,$isSub=false){
		if ($isSub){
			$sql = 'update DesignerProperty set CommentNum=CommentNum-'.$num.' where DesignerId=%s';
		}else {
			$sql = 'update DesignerProperty set CommentNum=CommentNum+'.$num.' where DesignerId=%s';
			
			$additionalSql = "insert into DesignerAttentionRecord(DesignerId,UserId,CreateTime,RecordType) value(%s,%s,%s,%s)";
			$this->query($additionalSql,array($designerId,$userId,date('Y-m-d H:i:s'),\haibao\cms\model\data\designer\DesignerAttentionRecord::RECORD_TYPE_COMMENT));
		}
		$this->query($sql,array($designerId));
	}
	public function addDesigner($designerModel,$syncOld = true){
	    $this->beginTranscation();
	    try{
	        parent::add($designerModel);
	        $this->addDesignerProperty($designerModel->Id);
			$this->addDesignerRelBrand($designerModel);
			$this->addDesignerRelCelebrity($designerModel);
			
	    }catch (\Exception $e) {
	        $this->rollback();
	        throw $e;
	    }
	    $this->endtranscation();
	    
	    return $designerModel;
	}
	
	public function getnum(){
	    
	}
	/**
	 * 根据标签ID更新设计师信息
	 * @param : Array $arrSet
	 * @param : Object \haibao\cms\model\filter\deisginer\designer $filter
	 * @param : Object \haibao\cms\model\data\designer\Designer $model
	 */
	public function updateDesignerByFilter($arrSet,$filter,$model = null){
	
	    $this->beginTranscation();
	    try{
	        $this->update($arrSet,$filter);
	
	    }catch (\Exception $e) {
	        $this->rollback();
	        throw $e;
	    }
	    $this->endTranscation();
	
	}
	
	public function getDesignerInfoById($designerId){
	    
	    $designerInfo = $designerBrandInfo = $designerCelebrityInfo = null;
	    
	    $designerFilter = new DesignerFilter();
	    $designerInfo = $this->getOneById($designerId);
	    
	    $designerRelBrandFilter = new DesignerRelBrandFilter();
	    $designerRelBrandData = new \haibao\cms\data\Designer();
	    $designerRelBrandFilter->select(array(
	        DesignerRelBrandFilter::CONDITION_FIELD_NAME_ID,
	        DesignerRelBrandFilter::CONDITION_FIELD_NAME_DESIGNER_ID,
	        DesignerRelBrandFilter::CONDITION_FIELD_NAME_BRAND_ID,
	        DesignerRelBrandFilter::CONDITION_FIELD_NAME_REL_TYPE,
	    ));
	    $designerRelBrandFilter->where(DesignerRelBrandFilter::CONDITION_FIELD_NAME_DESIGNER_ID, \haibao\frame\data\query\Condition::CONDITION_EQUAL, $designerId);
	    $designerBrandInfo = $designerRelBrandData->getAll($designerRelBrandFilter);
	    
	    $esignerRelCelebrityFilter = new DesignerRelCelebrityFilter();
	    $esignerRelCelebrityData = new \haibao\cms\data\Designer();
	    $esignerRelCelebrityFilter->select(array(
	        DesignerRelCelebrityFilter::CONDITION_FIELD_NAME_ID,
	        DesignerRelCelebrityFilter::CONDITION_FIELD_NAME_DESIGNER_ID,
	        DesignerRelCelebrityFilter::CONDITION_FIELD_NAME_CELEBRITY_ID,
	        DesignerRelCelebrityFilter::CONDITION_FIELD_NAME_REL_TYPE,
	    ));
	    
	    $esignerRelCelebrityFilter->where(DesignerRelCelebrityFilter::CONDITION_FIELD_NAME_DESIGNER_ID, \haibao\frame\data\query\Condition::CONDITION_EQUAL, $designerId);
	    $designerCelebrityInfo = $esignerRelCelebrityData->getAll($esignerRelCelebrityFilter);
	   
	    $brandIdArr = array();
	    if($designerBrandInfo){
	        foreach ($designerBrandInfo as $val){
	             array_push($brandIdArr, $val->BrandId);
	        }
	        $designerBrandArr = \haibao\cms\business\Brand::getBrandByIds($brandIdArr);
	        if($designerBrandArr){
	            foreach ($designerBrandInfo as $val){
	                $val->nameCn = $designerBrandArr[$val->BrandId]->NameCN;
	                $val->nameEn = $designerBrandArr[$val->BrandId]->NameEN;
	            } 
	        }
	    }
	    
	    $celebrityArr = $designerCelebrityArr = $tempCnArr = $tempEnArr = array();
	    if($designerCelebrityInfo){
	        foreach ($designerCelebrityInfo as $val){
	            array_push($celebrityArr, $val->CelebrityId);
	        }
	        $celebrityFilter = new \haibao\cms\model\filter\Celebrity();
	        $celebrityFilter->select(array(
	            \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_ID,
	            \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_CN,
	            \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_EN,
	        ));
	        $celebrityFilter->where(\haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_IN,$celebrityArr);
	        $designerCelebrityArr = \haibao\cms\business\Celebrity::getAll($celebrityFilter);
	        if($designerCelebrityArr){
	            foreach ($designerCelebrityArr as $val){
	                $tempCnArr[$val->Id] = $val->NameCn;
	                $tempEnArr[$val->Id] = $val->NameEn;
	            }
	            foreach ($designerCelebrityInfo as $val){
	                $val->nameEn =$tempEnArr[$val->CelebrityId];
	                $val->nameCn =$tempCnArr[$val->CelebrityId];
	            }
	        }
	    }
	    
	    $designerInfo->DesignerRelBrand = $designerBrandInfo;
	    $designerInfo->DesignerRelCelebrity = $designerCelebrityInfo;
	    return $designerInfo;
	}
	
	public function updateDesignerById($designerModel){
	    $designerArr = $this->packageDesignerFilter($designerModel);
	    $designerFilter = new DesignerFilter();
	    $designerRelBrandFilter = new DesignerRelBrandFilter();
	    $esignerRelCelebrityFilter = new DesignerRelCelebrityFilter();
	    $designerFilter->where($designerFilter::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL, $designerModel->Id);
	    $this->begintranscation();
	    try{
	        $this->updateById($designerModel->Id,$designerArr);
            $this->addDesignerRelBrand($designerModel);
            $this->addDesignerRelCelebrity($designerModel);
			
	    } catch (\Exception $e){
	        $this->rollback();
	    }
	    $this->endtranscation();
	}
	public function getDesignerProperty($designerId){
		$designerId = (array)$designerId;
		$designerPropertyArr = array();
		$designerStr = preg_replace('/\d+/', '%s', implode(',',$designerId));
		$result = $this->query("select DesignerId,EditFansNum,ClickNum,EditClickNum from DesignerProperty where DesignerId in ($designerStr)", $designerId);
		while ($result->fetch_assoc()){
			$temp = array();
			$temp['FansNum'] = $result->getData('EditFansNum');
			$temp['ClickNum'] = $result->getData('ClickNum');
			$temp['EditClickNum'] = $result->getData('EditClickNum');
			$designerPropertyArr[$result->getData('DesignerId')] = $temp;
		}
		return $designerPropertyArr;
	}
	
	/**
	 * 获取设计师的Id列表
	 * @param unknown $designerModel
	 * @return multitype:NULL
	 */
	public function getAllDesignerIdByWeight(){
		$cache = new \haibao\cms\cache\Designer();
		$arrDesignerId = $cache->getDesignerIdsCache();
		if(!$arrDesignerId){
			$arrDesignerInfo = array();
			$arrDesignerId = array();
			$arrTagId = array();
			$sql = 'select b.Id,b.TagId,s.WeightCount from Designer as b left join DesignerProperty as s on b.Id = s.DesignerId where b.Status=%s order by s.WeightCount desc';
			$result = $this->query($sql,array(\haibao\cms\model\data\designer\Designer::STATUS_ENABLE));
			while ($result->fetch_assoc()){
				$arrTagId[] = $result->getData('TagId');
				$arrDesignerInfo[$result->getData('Id')] = $result->getData('TagId');
			}
			
			$data = new \haibao\cms\data\Tag();
			$topPicIds = $data->getTopicIdByTagId($arrTagId);
			foreach($arrDesignerInfo as $designerId=>$designerTagId){
				if(isset($topPicIds[$designerTagId]) && $topPicIds[$designerTagId]){
					$arrDesignerId[] = $designerId;
				}
			}
			$cache->setDesignerIdsCache($arrDesignerId);
		}
		return $arrDesignerId;
	}
	
	private function packageDesignerFilter($designerModel){
	  
	    $designerArr = array(
	        DesignerFilter::CONDITION_FIELD_NAME_CATEGORY_TAGID => $designerModel->CategoryTagId,
	        DesignerFilter::CONDITION_FIELD_NAME_TAG_ID => $designerModel->TagId,
	        DesignerFilter::CONDITION_FIELD_NAME_TOPIC_ID => $designerModel->TopicId,
	        DesignerFilter::CONDITION_FIELD_NAME_IMGID => $designerModel->ImgId,
	        DesignerFilter::CONDITION_FIELD_NAME_DESCRIPTION => $designerModel->Description,
	        DesignerFilter::CONDITION_FIELD_NAME_NAMECN => $designerModel->NameCN,
	        DesignerFilter::CONDITION_FIELD_NAME_NAMEEN => $designerModel->NameEN,
	        DesignerFilter::CONDITION_FIELD_NAME_PINYINCN => $designerModel->PinyinCN,
	        DesignerFilter::CONDITION_FIELD_NAME_PINYINEN => $designerModel->PinyinEN,
	        DesignerFilter::CONDITION_FIELD_NAME_BIRTHDAY => isset($designerModel->Birthday)?$designerModel->Birthday:null,
	        DesignerFilter::CONDITION_FIELD_NAME_XINGZUO => $designerModel->XingZuo,
	        DesignerFilter::CONDITION_FIELD_NAME_GENDER => $designerModel->Gender,
	        DesignerFilter::CONDITION_FIELD_NAME_REGION => $designerModel->Region,
	        DesignerFilter::CONDITION_FIELD_NAME_IDENTITY => $designerModel->Identity,
	        DesignerFilter::CONDITION_FIELD_NAME_STATUS => $designerModel->Status,
	        DesignerFilter::CONDITION_FIELD_NAME_ISBRAND => $designerModel->IsBrand,
	        DesignerFilter::CONDITION_FIELD_NAME_CREATEBY => $designerModel->CreateBy,
	        DesignerFilter::CONDITION_FIELD_NAME_UPDATETIME => $designerModel->UpdateTime,
	    );
	    return $designerArr;
	}
	
	private function addDesignerRelBrand($designerModel){
	   
	    $delBrandIdArr = $this->delDesignerRelBrand($designerModel);
	  
	    $brandIdArr = $resultArr = $lastBrandIdArr = $oneArr = $twoArr = array();
        foreach ($designerModel->DesignerRelBrand as $brandV){
             if($brandV->BrandId){
                 array_push($brandIdArr, $brandV->BrandId);
             }
         }
         
         $oneArr = array_diff($brandIdArr, $delBrandIdArr);
         $twoArr = array_diff($delBrandIdArr,$brandIdArr);
         if(!empty($oneArr) || !empty($twoArr)){
             if(count($delBrandIdArr)<=count($brandIdArr)){
                 $resultArr = array_diff($brandIdArr, $delBrandIdArr);
                 $lastBrandIdArr = array_merge($delBrandIdArr, $resultArr);
             }else{
                 $resultArr = array_diff($delBrandIdArr,$brandIdArr);
                 $lastBrandIdArr = array_merge($brandIdArr, $resultArr);
             }
          }

        if($lastBrandIdArr){
            $this->updateBrandTime($lastBrandIdArr);
        }
        if($brandIdArr){
            $designerRelBrandModel = new DesignerRelBrandData();
            $this->addAll($designerModel->DesignerRelBrand);
        }     
        
      	$this->setBrandsCache();
       	$this->setBrandsCache(self::$all);

	}
	
	private function addDesignerRelCelebrity($designerModel){
	    $delCelebrityIdArr = $this->delDesignerRelCelebrity($designerModel);
	    $celebrityIdArr = $resultArr = $lastCelebrityIdArr = $oneArr = $twoArr = array();
	    foreach ($designerModel->DesignerRelCelebrity as $celebrityV){
	        if($celebrityV->CelebrityId){
	            array_push($celebrityIdArr, $celebrityV->CelebrityId);
	        }
	    }
	    $oneArr = array_diff($celebrityIdArr, $delCelebrityIdArr);
	    $twoArr = array_diff($delCelebrityIdArr,$celebrityIdArr);
	    if(!empty($oneArr) || !empty($twoArr)){
    	    if(count($delCelebrityIdArr)<=count($celebrityIdArr)){
    	        $resultArr = array_diff($celebrityIdArr, $delCelebrityIdArr);
    	        $lastCelebrityIdArr = array_merge($delCelebrityIdArr, $resultArr) ;
    	    }else{
    	        $resultArr = array_diff($delCelebrityIdArr,$celebrityIdArr);
    	        $lastCelebrityIdArr = array_merge($celebrityIdArr, $resultArr) ;
    	    }
	    }
	    
        if($lastCelebrityIdArr){
           $this->updateCelebrityTime($lastCelebrityIdArr);
        }
        if($celebrityIdArr){
            $designerRelCelebrityModel = new DesignerRelCelebrityData();
            $this->addAll($designerModel->DesignerRelCelebrity);
        }
        
	}
	
	private function delDesignerRelBrand($designerModel){

        $sql = 'select * from `DesignerRelBrand` where DesignerId = %s';
	    $result = $this->query($sql,array($designerModel->Id));
	    $brandIdTempArr = array();
	    
	    while ($row = $result->fetch_assoc()){
	        array_push($brandIdTempArr, $result->getData('BrandId'));
	    }
	    
	    if($brandIdTempArr){
	        $sql = 'delete from `DesignerRelBrand` where DesignerId = %s';
	        $this->query($sql,array($designerModel->Id));
	    }
	    
	    return $brandIdTempArr;
	}

	private function delDesignerRelCelebrity($designerModel){
	    
	    $sql = 'select * from `DesignerRelCelebrity` where DesignerId = %s';
	    $result = $this->query($sql,array($designerModel->Id));
	    $temp = array();
	    while ($row = $result->fetch_assoc()){
	        array_push($temp, $result->getData('CelebrityId'));
	    }
	    if($temp){
	        $sql = 'delete from `DesignerRelCelebrity` where DesignerId = %s';
	        $this->query($sql,array($designerModel->Id));
	    }
	    return $temp;
	}
	
	private function updateBrandTime($brandIdTempArr){
	    $nowTime = date('Y-m-d H:i:s');
	    $brandstr = preg_replace('/(\d+)/', '%s', implode(',', $brandIdTempArr));
	    $sql = "update Brand set UpdateTime = '".$nowTime."' where Id in (".$brandstr.")";
	    $this->query($sql, $brandIdTempArr);
	}
	
	private function updateCelebrityTime($celebrityIdArr){
	    $nowTime = date('Y-m-d H:i:s');
	    $celebritystr = preg_replace('/(\d+)/', '%s', implode(',', $celebrityIdArr));
	    $sql = "update Celebrity set UpdateTime = '".$nowTime."' where Id in (".$celebritystr.")";
	    $this->query($sql, $celebrityIdArr);
	}
    public function delDesignerById($id,$status){
        $this->updateById($id, $status);
    }
    
    private function addDesignerProperty($designerId){
        $sql = 'insert into DesignerProperty(`DesignerId`) values(%s)';
        $this->query($sql,array($designerId));
    }
    
    public function getLibraryDesignerRecommend(){
	    $sql = 'SELECT
                	DesignerTagId
                FROM
                	(
                		SELECT
                			DesignerTagId,
                			PublishTime
                		FROM
                			InformationDesigner
                		WHERE
                			IsPrimaiy = 1
                		ORDER BY
                			PublishTime DESC
                		LIMIT 20
                	) AS c
                GROUP BY
                	c.DesignerTagId
                ORDER BY
                	PublishTime DESC
                LIMIT 12';
	    $designerResult = $this->query($sql);
	    $designerIdArr = array();
	    while($row = $designerResult->fetch_assoc()){
	        $designerIdArr[] = $row['DesignerTagId'];
	    }
	    return $designerIdArr;
	}
}